package com.lenovo.testreport.user.controller;

import com.lenovo.session.LevelControl;
import com.lenovo.testreport.user.model.MessageCenter;
import com.lenovo.testreport.user.model.Userinfo;
import com.lenovo.testreport.user.service.RedisUserService;
import com.lenovo.testreport.user.service.MessageService;
import com.lenovo.testreport.user.service.UserService;
import com.lenovo.testreport.user.service.UserServiceImpl;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CJF
 * @date 2018/10
 * <p>
 * 对用户表进行删改查操作
 */
@Controller
@RequestMapping("/FindAndUpdate")
public class FindAndUpdate {
    @Autowired
    private UserService userService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private LevelControl LEVELCONTROL;

    @Autowired
    private RedisUserService redisUserService;

    //根据用户名查看单个用户信息
    @RequestMapping(value = "/FindUserByName", method = RequestMethod.POST)
    public @ResponseBody
    Userinfo FindUserByName(HttpServletRequest request) {
        String key = "Lenovo-sessionId:" + request.getSession().getId();
        return (Userinfo) (redisTemplate.opsForValue().get(key));
    }

    //查看所有用户信息
    @RequestMapping(value = "/FindAllUser", method = RequestMethod.POST)
    public @ResponseBody
    List<Userinfo> FindAllUser(HttpServletRequest request) {
        List<Userinfo> list = new ArrayList<>();
        if (!LEVELCONTROL.checkAdminSession(request)) {
            return list;
        }
        list = userService.FindAllUser();
        return list;

    }

    //用户修改密码
    @RequestMapping(value = "/UpdateUser", method = RequestMethod.POST)
    public @ResponseBody
    String UpdateUser(HttpServletRequest request) {
        String old_password = request.getParameter("old_password");
        String new_password = request.getParameter("new_password");
        String key = "Lenovo-sessionId:" + request.getSession().getId();
        Userinfo user = (Userinfo) redisTemplate.opsForValue().get(key);
        if (user == null) {
            return "您还未登录！";
        }
        if (user.getPassword().equals(old_password) == false) {
            return "用户名或原密码错误！";
        } else {
            user.setPassword(new_password);
            int result = userService.modifyUser(user);
            if (result > 0) {
                redisTemplate.delete(key);
                messageService.AddMessageRecord(new MessageCenter(request.getSession().getAttribute("User").toString(), "修改了自己的密码", "user-normal"));
                request.getSession().setAttribute("User", null);
                return "修改成功！请重新登录！";
            } else {
                return "修改失败！";
            }
        }

    }

    //管理员权限修改用户密码
    @RequestMapping(value = "/UpdateUserByAdmin", method = RequestMethod.POST)
    public @ResponseBody
    String UpdateUserByAdmin(HttpServletRequest request) {
        if (!LEVELCONTROL.checkAdminSession(request)) {
            return "没有操作权限";
        }
        String name = request.getParameter("username");
        String pwd = request.getParameter("password");
        Userinfo user = userService.findUserByName(name);
        user.setPassword(pwd);
        int result = userService.modifyUser(user);
        if (result > 0) {
            messageService.AddMessageRecord(new MessageCenter(request.getSession().getAttribute("User").toString(), "修改了用户" + name + "的密码", "user-admin"));

            return "修改成功！密码已生效！更新缓存中！";
        } else {
            return "修改失败！";
        }
    }

    //管理员权限删除用户
    @RequestMapping(value = "/DeleteUser", method = RequestMethod.POST)
    public @ResponseBody
    String DeleteUser(HttpServletRequest request) {
        if (!LEVELCONTROL.checkAdminSession(request)) {
            return "没有操作权限";
        }
        int uid = Integer.valueOf(request.getParameter("uid"));
        int result = userService.removeUser(uid);
        if (result > 0) {
            redisUserService.deleteUser(uid);
            messageService.AddMessageRecord(new MessageCenter(request.getSession().getAttribute("User").toString(), "删除了id为:" + uid + "的用户", "user-admin"));
            return "删除成功！";
        } else {
            return "删除失败！";
        }
    }

    /**
     * 管理员更改用户权限(新)
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/update/user/levelnum", method = RequestMethod.POST)
    public @ResponseBody
    String updateUserLevelNum(HttpServletRequest request) {
        try {
            if (!LEVELCONTROL.checkAdminSession(request)) {
                return "没有操作权限";
            }
            String codes = request.getParameter("codes");
            Integer uid = Integer.valueOf(request.getParameter("uid"));
            Integer levelnum = Integer.valueOf(request.getParameter("levelnum"));
            Userinfo user = new Userinfo();
            user.setUid(uid);
            String[] tempcodes = codes.split(",");
            int[] codes2 = new int[tempcodes.length];
            for (int i = 0; i < tempcodes.length; i++) {
                codes2[i] = Integer.valueOf(tempcodes[i]);
            }
            Integer newLevelNum = UserServiceImpl.ChangeLevelNum(codes2, levelnum);
            user.setLevelnum(newLevelNum);
            int result = userService.modifyUser(user);
            if (result > 0) {
                messageService.AddMessageRecord(new MessageCenter(request.getSession().getAttribute("User").toString(), "修改了id为:" + uid + "的用户的权限码值--->" + newLevelNum, "user-admin"));
                // 待完善
                //  redis_user_service.deleteUser(uid);
                return "修改成功！请被修改的用户重新登录！";

            } else {
                return "修改失败！";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "系统繁忙，请稍后再试!";
        }

    }


    //管理员权限更新用户权限等级
    @RequestMapping(value = "/UpdateUserLevel", method = RequestMethod.POST)
    public @ResponseBody
    String UpdateUserLevel(HttpServletRequest request) {
        if (!LEVELCONTROL.checkAdminSession(request)) {
            return "没有操作权限";
        }
        int uid = Integer.valueOf(request.getParameter("uid"));
        int newlevel = Integer.valueOf(request.getParameter("level"));
        Userinfo user = userService.findUserById(uid);
        user.setLevel(newlevel);
        int result = userService.modifyUser(user);
        if (result > 0) {
            messageService.AddMessageRecord(new MessageCenter(request.getSession().getAttribute("User").toString(), "修改了id为:" + uid + "的用户的权限等级--->" + newlevel, "user-admin"));
            return "修改成功！权限已生效，缓存更新中！";

        } else {
            return "修改失败！";
        }
    }


}
